package web;

import bean.Items;
import bean.Users;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import service.Impl.UserServiceImpl;
import service.UserService;
import utils.BianHaoUtils;

import javax.lang.model.type.DeclaredType;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.sql.Date;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;

/**
 * @author 栋
 * @date 2022/11/21
 * @description
 */
@WebServlet("/applicationitemsServlet")
public class ApplicationitemsServlet extends HttpServlet {
    UserService userService=new UserServiceImpl();
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        Users user = (Users)req.getSession().getAttribute("user");
        //判断是否在黑名单
        if(userService.isInBlacklist(user.getUser_id())){
            req.setAttribute("msg","你正处在黑名单中，不可上架商品");
            req.getRequestDispatcher("/pages/items/applicationItems.jsp").forward(req, resp);
        }else{
            //1 先判断上传的数据是否多段数据（只有是多段的数据，才是文件上传的）
            if (ServletFileUpload.isMultipartContent(req)) {
//           创建FileItemFactory工厂实现类
                FileItemFactory fileItemFactory = new DiskFileItemFactory();
                // 创建用于解析上传数据的工具类ServletFileUpload类
                ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
                //反射，用来设置类的属性值
                Class<Items> itemsClass = Items.class;
                Items item=new Items();
                item.setItem_id(BianHaoUtils.getItemId());

                item.setOwer_id(user.getUser_id());
                item.setApp_date(Date.valueOf(LocalDate.now()));
                item.setApp_time(Time.valueOf(LocalTime.now()));
                try {
                    // 解析上传的数据，得到每一个表单项FileItem
                    List<FileItem> list = servletFileUpload.parseRequest(req);
                    // 循环判断，每一个表单项，是普通类型，还是上传的文件
                    for (FileItem fileItem : list) {

                        if (fileItem.isFormField()) {
                            // 普通表单项

                            String fieldName = fileItem.getFieldName();
                            // 参数UTF-8.解决乱码问题
                            String value = fileItem.getString("UTF-8");
                            Field declaredField = itemsClass.getDeclaredField(fieldName);
                            Type genericType = declaredField.getGenericType();
                            if (genericType.toString().equals("class java.lang.Integer")){
                                Integer v = Integer.valueOf(value);
                                declaredField.setAccessible(true);
                                declaredField.set(item,v);
                            }else if(genericType.toString().equals("class java.math.BigDecimal")){
                                BigDecimal bigDecimal=BigDecimal.valueOf(Double.valueOf(value));
                                declaredField.setAccessible(true);
                                declaredField.set(item,bigDecimal);
                            }else{
                                declaredField.setAccessible(true);
                                declaredField.set(item,value);
                            }

                        } else {
                            // 上传的文件
                            String fieldName = fileItem.getFieldName();
                            String fileName = fileItem.getName();
                            String value="img/items/"+item.getItem_id()+".jpg";
                            Field declaredField = itemsClass.getDeclaredField(fieldName);
                            declaredField.setAccessible(true);
                            declaredField.set(item,value);
                            ServletContext servletContext = getServletConfig().getServletContext();
                            String contextPath = servletContext.getRealPath("img/items/");

                            fileItem.write(new File( contextPath+item.getItem_id()+".jpg"));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(item.getMethod().equals("自取")){
                    item.setMethod("自取"+user.getAddress());
                }
                userService.applicationItems(item);
                req.getRequestDispatcher("/pages/items/applicationSuc.jsp").forward(req, resp);

            }
        }


    }
}
